package com.lianxian.xindong.commonres.observer;


import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.hxb.library.utils.LogUtils;

import java.lang.reflect.Type;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import com.lianxian.xindong.commonres.entity.ResultBaseBean;
import com.lianxian.xindong.commonsdk.http.Api;

/**
 * @作者： HeXingBo
 * @时间： 2022/11/14 17:03
 * @描述：
 */
public abstract class MyHttpResultObserver<T> extends ErrorHandleSubscriber<ResultBaseBean<T>> {

    public static Gson gson = new GsonBuilder().
            registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
                @Override
                public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                    if (src == src.longValue())
                        return new JsonPrimitive(src.longValue());
                    return new JsonPrimitive(src);
                }
            }).create();

    public MyHttpResultObserver(RxErrorHandler rxErrorHandler) {
        super(rxErrorHandler);
    }

    @Override
    public void onNext(ResultBaseBean<T> httpResult) {
        LogUtils.debugInfo("-----hxb---->" + httpResult.toString());
        if (httpResult.getCode() == Api.REQUEST_SUCCESS) {
            //请求成功
            onResult(httpResult.getData());
        } else {
            if (httpResult.getCode() == Api.REQUEST_LOGIN_OUT) {
                onError(new Throwable("登录已失效，请重新登录"));
            } else {
                onError(new Throwable(TextUtils.isEmpty(httpResult.getMsg()) ? "未知错误" : httpResult.getMsg()));
            }
        }
    }

    public abstract void onResult(T result);

    @Override
    public void onError(Throwable t) {
        super.onError(t);
    }
}
